package com.leyou.order.interceptor;

import com.leyou.common.auth.pojo.UserHolder;
import com.leyou.common.constant.LyConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class UserInterceptor implements HandlerInterceptor {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从请求头中获取用户id的字符串
        String userIdStr = request.getHeader(LyConstants.USER_HOLDER_KEY);
        if(StringUtils.isEmpty(userIdStr)){
            log.error("【拦截器获取用户id】失败！");
            //不允许访问处理器
            return false;
        }
        //将字符串id转成Long类型
        Long userId = Long.valueOf(userIdStr);
        log.info("【拦截器获取用户id】成功！");
        //将用户id放入线程的局部变量中
        UserHolder.setUserId(userId);
        return true;
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        UserHolder.removeUserId();
    }

}
